package easy.有效的括号;

import java.util.*;

public class Solution {
    public boolean isValid(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)) {//右括号
                //右括号前面没有左括号 || 括号不匹配
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    return false;
                }
                //左右括号匹配
                stack.pop();
            } else {
                //左括号入栈
                stack.push(ch);
            }
        }
        return stack.isEmpty();

    }

    public static void main(String[] args) {
        String s = "([])";
        String s2 = "([)]";
        Solution solution = new Solution();
        System.out.println(solution.isValid(s));
        System.out.println(solution.isValid(s2));
    }
}
